package com.jeesite.modules.tk.web;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icecold.utils.DateUtils;
import com.icecold.utils.file.ImageCompressor;
import com.icecold.utils.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.em.MyTaskStatus;
import com.jeesite.modules.em.TaskStatus;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.ic.service.IcUserService;
import com.jeesite.modules.tk.entity.TkMyTask;
import com.jeesite.modules.tk.service.TkMyTaskService;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.tk.entity.TkTask;
import com.jeesite.modules.tk.service.TkTaskService;
import org.springframework.web.multipart.MultipartFile;

/**
 * tk_taskController
 * @author 李寒冰
 * @version 2024-12-05
 */
@Controller
@RequestMapping(value = "${adminPath}/tk/tkTask")
public class TkTaskController extends BaseController {

	@Autowired
	private TkTaskService tkTaskService;
    @Autowired
    private IcUserService icUserService;

	@Value("${pic.host}")
	private String picHost;

	@Value("${pic.uploadPath}")
	private String uploadPath;
    @Autowired
    private TkMyTaskService tkMyTaskService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public TkTask get(String id, boolean isNewRecord) {
		return tkTaskService.get(id, isNewRecord);
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("tk:tkTask:view")
	@RequestMapping(value = {"listPt", ""})
	public String listPt(TkTask tkTask, Model model) {
		model.addAttribute("tkTask", tkTask);
		return "modules/tk/tkTaskListPt";
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("tk:tkTask:view")
	@RequestMapping(value = "listDataPt")
	@ResponseBody
	public Page<TkTask> listDataPt(TkTask tkTask, HttpServletRequest request, HttpServletResponse response) {
		tkTask.setPage(new Page<>(request, response));
		tkTask.setType("3");
		Page<TkTask> page = tkTaskService.findPage(tkTask);
		List<TkTask> list = page.getList();
		for (TkTask task : list) {

		}
		return page;
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("tk:tkTask:view")
	@RequestMapping(value = {"list", ""})
	public String list(TkTask tkTask, Model model) {
		model.addAttribute("tkTask", tkTask);
		return "modules/tk/tkTaskList";
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("tk:tkTask:view")
	@RequestMapping(value = {"taskInfo", ""})
	public String taskInfo(TkTask tkTask, Model model) {
		tkTask = tkTaskService.get(tkTask.getId());
		String userId = tkTask.getUserId();
		IcUser icUser = icUserService.get(userId);
		tkTask.setIcUser(icUser);
		String buzhouList = tkTask.getBuzhouList();
		if(StringUtils.isNotEmpty(buzhouList)){
			JSONArray jsonArray = JSONArray.parseArray(buzhouList);
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject1 = jsonArray.getJSONObject(i);
				String type = TkTask.BuzhouType.getNameByCode(jsonObject1.getString("type"));
				jsonObject1.put("type", type);
				//图片加前缀

				String pics = jsonObject1.getString("pic");
				if(StringUtils.isNotEmpty(pics) && !pics.startsWith("http")){
					pics = picHost+pics;
					jsonObject1.put("pic", pics);
				}
			}
			tkTask.setBuzhouList(jsonArray.toJSONString());
		}
		model.addAttribute("tkTask", tkTask);
		String buzhouList1 = tkTask.getBuzhouList();
		if(StringUtils.isNotEmpty(buzhouList1)){
			JSONArray jsonArray1 = JSONArray.parseArray(buzhouList1);
			model.addAttribute("buzhouList", jsonArray1);
		}
		return "modules/tk/tkTaskInfo";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("tk:tkTask:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<TkTask> listData(TkTask tkTask, HttpServletRequest request, HttpServletResponse response) {
		tkTask.setPage(new Page<>(request, response));
		tkTask.setXZBTaskIdIsNull();
		Page<TkTask> page = tkTaskService.findPage(tkTask);
		List<TkTask> list = page.getList();
		for (TkTask task : list) {
			task.setIcUser(icUserService.get(task.getUserId()));
		}
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("tk:tkTask:view")
	@RequestMapping(value = "form")
	public String form(TkTask tkTask, Model model) {
		model.addAttribute("tkTask", tkTask);
		return "modules/tk/tkTaskForm";
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("tk:tkTask:view")
	@RequestMapping(value = "formPt")
	public String formPt(TkTask tkTask, Model model) {
		if(StringUtils.isNotEmpty(tkTask.getId())){
			tkTask = tkTaskService.get(tkTask.getId());
		}
		model.addAttribute("tkTask", tkTask);
		return "modules/tk/tkTaskForm";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("tk:tkTask:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TkTask tkTask) {
		tkTaskService.save(tkTask);
		return renderResult(Global.TRUE, text("保存tk_task成功！"));
	}

	/**
	 * 保存平台任务
	 */
	@RequiresPermissions("tk:tkTask:edit")
	@PostMapping(value = "savePtTask")
	@ResponseBody
	public String savePtTask(@Validated TkTask tkTask) {
		String buzhouList = tkTask.getBuzhouList();
		if(StringUtils.isEmpty(buzhouList)){
			return renderResult(Global.FALSE, text("请填写任务步骤！"));
		}
		JSONArray jsonArray = JSONArray.parseArray(buzhouList);
		boolean lose = true;
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject1 = jsonArray.getJSONObject(i);
			String type = jsonObject1.getString("type");
			//收集，截图
			if(type.equals("shouji") || type.equals("jietu")){
				lose = false;
			}
			String shuoming = jsonObject1.getString("shuoming");
			if(StringUtils.isEmpty(shuoming)){
				return renderResult(Global.FALSE, text("请完善步骤说明！"));
			}
			if(StringUtils.isEmpty(jsonObject1.getString("pic"))){
				if(type.equals("erweima")){
					return renderResult(Global.FALSE, text("请上传二维码！"));
				}

				if(type.equals("tuwen") || type.equals("jietu")){
					return renderResult(Global.FALSE, text("请上传图片！"));
				}
			}

			if(StringUtils.isEmpty(jsonObject1.getString("shuomingTwo"))){
				if(type.equals("wangzhi")){
					return renderResult(Global.FALSE, text("请输入网址！"));
				}
				if(type.equals("shuju")){
					return renderResult(Global.FALSE, text("请输入需要复制的数据！"));
				}
			}

		}
		if(lose){
			return renderResult(Global.FALSE, text("请至少添加一个收集信息或截图的步骤！"));
		}
		if(StringUtils.isEmpty(tkTask.getId()) || tkTask.getCreateTime()==null){
			tkTask.setCreateTime(new Date());
		}

		tkTaskService.savePtTask(tkTask);
		return renderResult(Global.TRUE, text("保存成功！"));
	}

	/**
	 * 删除数据
	 */
	@RequiresPermissions("tk:tkTask:edit")
	@RequestMapping(value = "updateTaskStatus")
	@ResponseBody
	public String updateTaskStatus(TkTask tkTask) {
		TkTask tkTask1 = tkTaskService.get(tkTask);
		tkTask1.setTaskStatus(tkTask.getTaskStatus());
		if(TaskStatus.YIJIESHU.getCode().equals(tkTask.getTaskStatus())){
			String id = tkTask1.getId();
			TkMyTask tkMyTask = new TkMyTask();
			tkMyTask.setTaskId(id);
			tkMyTask.setMyTaskStatus(MyTaskStatus.DAISHENHE.getCode());
			List<TkMyTask> list = tkMyTaskService.findList(tkMyTask);
			if(list.size()>0){
				return renderResult(Global.FALSE, text("尚有任务未审核，不可结束！"));
			}
		}
		tkTaskService.savePtTask(tkTask1);
		return renderResult(Global.TRUE, text("操作成功！"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("tk:tkTask:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TkTask tkTask) {
		tkTaskService.delete(tkTask);
		return renderResult(Global.TRUE, text("删除tk_task成功！"));
	}
	@RequestMapping(value = "fileUpload")
	@ResponseBody
	public String fileUpload(@RequestParam("file") MultipartFile file) {
		String originFileName = file.getOriginalFilename();
		String picName= IdGen.uuid();
		String suffix = originFileName.split("\\.")[1];

//        String destFileName = "/home/java/project/liuliangka/userfiles/taskpic/" + DateUtils.getDate() +"/"+ picName;
		String destFileName = uploadPath+"/userfiles/taskpic/" + DateUtils.getDate() +"/"+ picName;
		destFileName = destFileName +"."+ suffix;
		File destFile = new File(destFileName);
		destFile.getParentFile().mkdirs();
		try {
			FileUtil.writeBytes(file.getBytes(),destFileName);
			ImageCompressor.thumbnails(new File(destFileName),1000,-1,null);

		} catch (IOException e) {
			e.printStackTrace();
		}
		String online = picHost+"/userfiles/taskpic/" + DateUtils.getDate() +"/"+ picName+"."+ suffix;
		return renderResult(Global.TRUE, text(""),online);
	}
	
}